<template>
  <div class="sidebar-container">
    <!-- 精选推荐模块 -->
    <div class="module card">
      <div class="module-header">
        <h2><el-icon><Star /></el-icon> 精选推荐</h2>
        <div class="tabs-container">
          <el-radio-group
              v-model="activeRecommendationTab"
              size="small"
          >
            <el-radio-button label="resources">资源</el-radio-button>
            <el-radio-button label="activities">活动</el-radio-button>
          </el-radio-group>
        </div>
      </div>
      <div class="module-body">
        <div v-if="activeRecommendationTab === 'resources'" class="recommendation-list">
          <div
              v-for="(item, index) in resourceRecommendations"
              :key="index"
              class="recommendation-item"
              @click="handleRecommendationClick(item)"
          >
            <div class="recommendation-icon">
              <el-icon><component :is="getIconComponent(item.icon)" /></el-icon>
            </div>
            <div class="recommendation-details">
              <div class="recommendation-title">{{ item.title }}</div>
              <div class="recommendation-description">{{ item.description }}</div>
            </div>
          </div>
        </div>

        <div v-else class="activity-list">
          <div
              v-for="(activity, index) in activityRecommendations"
              :key="index"
              class="activity-item"
              @click="handleActivityClick(activity)"
          >
            <div class="activity-icon">
              <el-icon><component :is="getIconComponent(activity.icon)" /></el-icon>
            </div>
            <div class="activity-details">
              <div class="activity-title">{{ activity.title }}</div>
              <div class="activity-time">{{ activity.time }}</div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 新闻通知模块 -->
    <div class="module card">
      <div class="module-header">
        <h2><el-icon><Bell /></el-icon> 新闻通知</h2>
        <div class="tabs-container">
          <el-radio-group
              v-model="activeNewsTab"
              size="small"
          >
            <el-radio-button label="news">新闻</el-radio-button>
            <el-radio-button label="notices">通知</el-radio-button>
          </el-radio-group>
        </div>
      </div>
      <div class="module-body">
        <div v-if="activeNewsTab === 'news'" class="news-list">
          <div
              v-for="(news, index) in newsItems"
              :key="index"
              class="news-item"
              @click="handleNewsClick(news)"
          >
            <div class="news-badge" :class="news.type">{{ news.type === 'important' ? '重要' : '新闻' }}</div>
            <div class="news-content">
              <div class="news-title">{{ news.title }}</div>
              <div class="news-time">{{ news.time }}</div>
            </div>
          </div>
        </div>

        <div v-else class="notices-list">
          <div
              v-for="(notice, index) in notices"
              :key="index"
              class="notice-item"
              @click="handleNoticeClick(notice)"
          >
            <div class="notice-icon">
              <el-icon><BellFilled /></el-icon>
            </div>
            <div class="notice-content">
              <div class="notice-title">{{ notice.title }}</div>
              <div class="notice-time">{{ notice.time }}</div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 我的日程模块 -->
    <div class="module card">
      <div class="module-body calendar-module-body">
        <div class="calendar-container">
          <div class="calendar-header">
            <div v-for="day in weekDays" :key="day" class="calendar-day-header">
              {{ day }}
            </div>
          </div>
          <div class="calendar-grid">
            <div
                v-for="(day, index) in calendarDaysComputed"
                :key="index"
                class="calendar-day-wrapper"
                :class="{ 'has-note': day.isToday }"
            >
              <div
                  class="calendar-day"
                  :class="{
                    'current-month': day.isCurrentMonth,
                    'today': day.isToday
                  }"
                  @click="handleDayClick(day)"
                  @mouseenter="day.isToday ? showApiNote = true : null"
                  @mouseleave="day.isToday ? showApiNote = false : null"
              >
                <div class="day-number">{{ day.date.getDate() }}</div>
              </div>

              <!-- 将提示移到包装层，避免被裁剪 -->
              <div v-if="day.isToday" class="api-note-indicator" :class="{ 'show': showApiNote }">
                <el-tag type="warning" size="small">待开发</el-tag>
                <span class="note-text">日历事件接口待实现</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- 通知详情弹窗 -->
  <el-dialog
      v-model="noticeDetailVisible"
      :title="currentNotice?.title"
      width="60%"
      :before-close="handleCloseNoticeDetail"
  >
    <NoticeDetail
        v-if="currentNotice"
        :notice="currentNotice"
        tab-type="received"
        @close="noticeDetailVisible = false"
    />
  </el-dialog>

  <!-- 活动详情弹窗 -->
  <ActivityDetailDialog
      v-model:visible="activityDetailVisible"
      :activity-id="selectedActivityId"
  />
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { getSidebarData } from '@/api/teacher';
import { ElMessage } from 'element-plus';
import NoticeDetail from './NoticeDetail.vue';
import ActivityDetailDialog from './ActivityDetailDialog.vue';
import {
  Star, Bell, BellFilled,
  Document, DataBoard, DataAnalysis, VideoPlay, Picture,
  Trophy, Notebook, Cpu,  Flag
} from '@element-plus/icons-vue';

const router = useRouter();
const showApiNote = ref(false);

// 精选推荐选项卡
const activeRecommendationTab = ref('resources');
// 新闻通知选项卡
const activeNewsTab = ref('news');
// 日历相关数据
const selectedMonth = ref('');
const today = ref(new Date());
const weekDays = ['日', '一', '二', '三', '四', '五', '六'];

// 数据源改为从API获取
const resourceRecommendations = ref([]);
const activityRecommendations = ref([]);
const newsItems = ref([]);
const notices = ref([]);
const calendarDays = ref([]);

// 通知详情相关
const noticeDetailVisible = ref(false);
const currentNotice = ref(null);

// 活动详情相关
const activityDetailVisible = ref(false);
const selectedActivityId = ref(null);

// 图标映射表
const iconMap = {
  // 资源图标
  'Document': Document,
  'DataBoard': DataBoard,
  'DataAnalysis': DataAnalysis,
  'VideoPlay': VideoPlay,
  'Picture': Picture,
  // 活动图标
  'Trophy': Trophy,
  'Notebook': Notebook,
  'CPU': Cpu,
  'Flag': Flag,
  // 默认图标
  'BellFilled': BellFilled
};

// 获取图标组件
const getIconComponent = (iconName) => {
  return iconMap[iconName] || Document;
};

// 初始化数据
onMounted(async () => {
  // 初始化当前月份
  const year = today.value.getFullYear();
  const month = today.value.getMonth() + 1;
  selectedMonth.value = `${year}-${month.toString().padStart(2, '0')}`;

  // 获取侧边栏数据
  try {
    const response = await getSidebarData();
    if (response.data) {
      const data = response.data;

      // 设置推荐数据
      activeRecommendationTab.value = data.recommendations.activeTab;
      resourceRecommendations.value = data.recommendations.resourceRecommendations || [];
      activityRecommendations.value = data.recommendations.activityRecommendations || [];

      // 设置新闻通知数据
      activeNewsTab.value = data.newsNotices.activeTab;
      newsItems.value = data.newsNotices.newsItems || [];
      notices.value = data.newsNotices.notices || [];

      // 设置日历数据
      if (data.calendar) {
        selectedMonth.value = data.calendar.selectedMonth || selectedMonth.value;
        calendarDays.value = data.calendar.calendarDays || [];
      }
    }
  } catch (error) {
    console.error('获取侧边栏数据失败:', error);
    ElMessage.error('获取侧边栏数据失败');
  }
});

// 计算日历天数
const calendarDaysComputed = computed(() => {
  // 如果API返回了日历数据，使用API数据
  if (calendarDays.value.length > 0) {
    const days = [];
    const [year, month] = selectedMonth.value.split('-').map(Number);
    const firstDayOfMonth = new Date(year, month - 1, 1);
    const firstDayOfWeek = firstDayOfMonth.getDay();

    // 1. 添加上个月的日期
    const prevMonthLastDay = new Date(year, month - 1, 0).getDate();
    for (let i = 0; i < firstDayOfWeek; i++) {
      const date = new Date(year, month - 2, prevMonthLastDay - firstDayOfWeek + i + 1);
      days.push({
        date,
        isCurrentMonth: false,
        isToday: isSameDay(date, today.value),
        hasEvent: false
      });
    }

    // 2. 添加当月日期
    const currentMonthEvents = new Map();
    calendarDays.value.forEach(day => {
      const date = new Date(day.date);
      if (date.getMonth() + 1 === month) {
        currentMonthEvents.set(date.getDate(), day.hasEvent);
      }
    });

    const daysInMonth = new Date(year, month, 0).getDate();
    for (let i = 1; i <= daysInMonth; i++) {
      const date = new Date(year, month - 1, i);
      days.push({
        date,
        isCurrentMonth: true,
        isToday: isSameDay(date, today.value),
        hasEvent: currentMonthEvents.get(i) || hasEventOnDate(date)
      });
    }

    // 3. 添加下个月的日期
    const totalCells = 42;
    const remainingCells = totalCells - days.length;
    for (let i = 1; i <= remainingCells; i++) {
      const date = new Date(year, month, i);
      days.push({
        date,
        isCurrentMonth: false,
        isToday: isSameDay(date, today.value),
        hasEvent: false
      });
    }

    return days;
  }

  // 使用默认逻辑
  if (!selectedMonth.value) return [];

  const [year, month] = selectedMonth.value.split('-').map(Number);
  const firstDayOfMonth = new Date(year, month - 1, 1);
  const lastDayOfMonth = new Date(year, month, 0);
  const daysInMonth = lastDayOfMonth.getDate();
  const firstDayOfWeek = firstDayOfMonth.getDay();

  const days = [];
  const prevMonthLastDay = new Date(year, month - 1, 0).getDate();

  for (let i = firstDayOfWeek - 1; i >= 0; i--) {
    const date = new Date(year, month - 2, prevMonthLastDay - i);
    days.push({
      date,
      isCurrentMonth: false,
      isToday: isSameDay(date, today.value),
      hasEvent: false
    });
  }

  for (let i = 1; i <= daysInMonth; i++) {
    const date = new Date(year, month - 1, i);
    days.push({
      date,
      isCurrentMonth: true,
      isToday: isSameDay(date, today.value),
      hasEvent: hasEventOnDate(date)
    });
  }

  const nextMonthDays = 42 - days.length;
  for (let i = 1; i <= nextMonthDays; i++) {
    const date = new Date(year, month, i);
    days.push({
      date,
      isCurrentMonth: false,
      isToday: isSameDay(date, today.value),
      hasEvent: false
    });
  }

  return days;
});

// 工具函数
const isSameDay = (date1, date2) => {
  return date1.getFullYear() === date2.getFullYear() &&
      date1.getMonth() === date2.getMonth() &&
      date1.getDate() === date2.getDate();
};

const hasEventOnDate = (date) => {
  return false; // 去掉所有事件标记
};

// 处理推荐点击 - 根据type字段跳转到对应的资源详情页
const handleRecommendationClick = (item) => {
  console.log('打开推荐:', item.title);

  if (!item.type) {
    ElMessage.warning('该资源暂不支持预览');
    return;
  }

  // 路由映射配置 - 使用您提供的教师端路由
  const routeMap = {
    'pdf': '/teacher/fileViewerPDF',
    'doc': '/teacher/fileViewerWord',
    'docx': '/teacher/fileViewerWord',
    'ppt': '/teacher/fileViewerPPT',
    'pptx': '/teacher/fileViewerPPT',
    'xls': '/teacher/fileViewerExcel',
    'xlsx': '/teacher/fileViewerExcel',
    'video': '/teacher/fileViewerVideo',
    'image': '/teacher/fileViewerImage'
  };

  // 文件路径映射配置（根据实际情况调整）
  const filePathMap = {
    'video': '/pdfjs/test.mp4',
    'doc': '/pdfjs/test.docx',
    'docx': '/pdfjs/test.docx',
    'pdf': '/pdfjs/test.pdf',
    'ppt': '/pdfjs/test.pptx',
    'pptx': '/pdfjs/test.pptx',
    'xls': '/pdfjs/test.xlsx',
    'xlsx': '/pdfjs/test.xlsx',
    'image': '/pdfjs/test.jpg'
  };

  const routePath = routeMap[item.type] || '/teacher/resources';
  const filePath = filePathMap[item.type] || '/pdfjs/test.docx';

  router.push({
    path: routePath,
    query: {
      type: item.type,
      title: item.title,
      id: extractIdFromUrl(item.url),
      fileUrl: filePath
    }
  });
};
const extractIdFromUrl = (url) => {
  if (!url) return null;
  const match = url.match(/\/(\d+)$/);
  return match ? parseInt(match[1]) : null;
};
// 修改活动点击处理函数
const handleActivityClick = (activity) => {
  const activityId = extractIdFromUrl(activity.url);

  // 检查活动是否有ID，如果有则显示详情弹窗
  if (activityId) {
    selectedActivityId.value = activityId;
    activityDetailVisible.value = true;
  } else if (activity.url) {
    // 如果没有ID但有URL，则在新窗口打开
    window.open(activity.url, '_blank');
  } else {
    ElMessage.info('该活动暂无详细信息');
  }
};

const handleNewsClick = (news) => {
  console.log('打开新闻:', news.title);
};

// 处理通知点击 - 使用NoticeDetail.vue组件
const handleNoticeClick = (notice) => {
  console.log('打开通知:', notice);

  // 设置当前通知数据
  currentNotice.value = {
    noticeId: notice.noticeId,
    title: notice.title,
    content: notice.content,
    typeName: notice.typeName,
    senderName: notice.senderName,
    createTime: notice.createTime || notice.time,
    description: notice.description
  };

  noticeDetailVisible.value = true;
};

// 关闭通知详情弹窗
const handleCloseNoticeDetail = () => {
  noticeDetailVisible.value = false;
  currentNotice.value = null;
};

const handleDayClick = (day) => {
  if (day.isCurrentMonth) {
    console.log('选择日期:', day.date.toLocaleDateString());
  }
};
</script>

<!-- 样式部分保持不变 -->
<style scoped>
.sidebar-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.module {
  background: #fff;
  border-radius: 8px;
  overflow: visible !important;  /* 修复溢出裁剪 */
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  transition: transform 0.3s ease, box-shadow 0.3s ease;
  min-height: 200px;
  display: flex;
  flex-direction: column;
}

.module:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

.module-header {
  position: relative;
  padding: 16px 20px;
  background: #1e62ec;
  color: white;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.module-header h2 {
  font-size: 18px;
  font-weight: 600;
  margin: 0;
  display: flex;
  align-items: center;
  gap: 10px;
}

.tabs-container {
  display: flex;
  align-items: center;
}

/* 选项卡样式 */
:deep(.el-radio-group) {
  margin-left: 10px;
}

:deep(.el-radio-button) {
  --el-radio-button-checked-bg-color: rgba(255, 255, 255, 0.2);
  --el-radio-button-checked-text-color: white;
  --el-radio-button-checked-border-color: transparent;
}

:deep(.el-radio-button__inner) {
  background: rgba(255, 255, 255, 0.1);
  border: none;
  color: rgba(255, 255, 255, 0.8);
  border-radius: 4px;
  padding: 5px 12px;
  font-size: 12px;
  transition: all 0.3s;
}

:deep(.el-radio-button__inner:hover) {
  color: white;
  background: rgba(255, 255, 255, 0.15);
}

:deep(.el-radio-button:first-child .el-radio-button__inner) {
  border-radius: 4px 0 0 4px;
}

:deep(.el-radio-button:last-child .el-radio-button__inner) {
  border-radius: 0 4px 4px 0;
}

.module-body {
  padding: 15px;
  flex-grow: 1;
  display: flex;
  flex-direction: column;
  overflow: visible !important;  /* 修复溢出裁剪 */
}

.calendar-module-body {
  position: relative;
  overflow: visible !important;
}

/* 精选推荐样式 */
.recommendation-list, .activity-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.recommendation-item, .activity-item {
  display: flex;
  align-items: center;
  padding: 10px;
  border-radius: 8px;
  background: #f9fafc;
  transition: all 0.3s;
  cursor: pointer;
}

.recommendation-item:hover, .activity-item:hover {
  background: #e8f4ff;
  transform: translateY(-2px);
}

.recommendation-icon, .activity-icon {
  width: 36px;
  height: 36px;
  background: #e6f1ff;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 10px;
  flex-shrink: 0;
}

.recommendation-icon .el-icon, .activity-icon .el-icon {
  font-size: 18px;
  color: #1e62ec;
}

.recommendation-details, .activity-details {
  flex-grow: 1;
  min-width: 0;
}

.recommendation-title, .activity-title {
  font-size: 13px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 4px;
}

.recommendation-description {
  font-size: 11px;
  color: #909399;
}

.activity-time {
  font-size: 11px;
  color: #909399;
}

/* 新闻通知样式 */
.news-list, .notices-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.news-item, .notice-item {
  display: flex;
  align-items: flex-start;
  padding: 8px;
  border-radius: 6px;
  background: #f9fafc;
  transition: all 0.3s;
  cursor: pointer;
}

.news-item:hover, .notice-item:hover {
  background: #e8f4ff;
}

.news-badge {
  min-width: 36px;
  padding: 2px 5px;
  border-radius: 4px;
  font-size: 11px;
  font-weight: 500;
  text-align: center;
  margin-right: 8px;
  flex-shrink: 0;
}

.news-badge.important {
  background: #fef0f0;
  color: #f56c6c;
}

.news-badge.normal {
  background: #f0f9eb;
  color: #67c23a;
}

.notice-icon {
  width: 30px;
  height: 30px;
  background: #e6f1ff;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 8px;
  flex-shrink: 0;
}

.notice-icon .el-icon {
  font-size: 16px;
  color: #1e62ec;
}

.news-content, .notice-content {
  flex-grow: 1;
}

.news-title, .notice-title {
  font-size: 12px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 2px;
}

.news-time, .notice-time {
  font-size: 10px;
  color: #909399;
}

/* 日历样式 - 修复部分 */
.calendar-container {
  display: flex;
  flex-direction: column;
}

.calendar-header {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  text-align: center;
  font-size: 12px;
  font-weight: 500;
  color: #606266;
  margin-bottom: 8px;
}

.calendar-grid {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  gap: 4px;
  overflow: visible !important;
  position: relative;
  z-index: 1;
}

/* 新增包装层样式 */
.calendar-day-wrapper {
  position: relative;
  aspect-ratio: 1/1;
  overflow: visible !important;
}

.calendar-day {
  aspect-ratio: 1/1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  border-radius: 6px;
  font-size: 12px;
  cursor: pointer;
  position: relative;
  transition: all 0.2s;
  width: 100%;
  height: 100%;
}

.calendar-day.current-month {
  background: #f5f7fa;
  color: #303133;
}

.calendar-day:not(.current-month) {
  background: #fafafa;
  color: #c0c4cc;
}

.calendar-day.today {
  background: #e6f1ff;
  color: #1e62ec;
  font-weight: 600;
}

.calendar-day:hover {
  background: #e8f4ff;
  transform: scale(1.05);
}

.day-number {
  font-size: 13px;
  z-index: 1;
}

/* 修改API标注样式 */
.api-note-indicator {
  position: absolute;
  top: -45px;
  left: 50%;
  transform: translateX(-50%);
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 4px;
  padding: 8px 12px;
  background: rgba(253, 246, 236, 0.98);
  border-radius: 6px;
  border: 1px dashed #e6a23c;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  z-index: 1000;
  opacity: 0;
  visibility: hidden;
  transition: all 0.3s ease;
  pointer-events: none;
  white-space: nowrap;
  min-width: max-content;
}

.api-note-indicator.show {
  opacity: 1;
  visibility: visible;
}

.note-text {
  font-size: 12px;
  font-weight: 500;
  color: #e6a23c;
}

/* 添加提示箭头 */
.api-note-indicator::after {
  content: '';
  position: absolute;
  bottom: -6px;
  left: 50%;
  transform: translateX(-50%);
  border-left: 6px solid transparent;
  border-right: 6px solid transparent;
  border-top: 6px solid #e6a23c;
}

/* 为今天日期添加特殊样式 */
.calendar-day.today:hover {
  background: #d4e7ff;
  box-shadow: 0 0 0 2px #e6a23c;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .module-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .tabs-container {
    width: 100%;
    justify-content: flex-end;
  }
}

@media (max-width: 992px) {
  .sidebar-container {
    flex-direction: row;
    flex-wrap: wrap;
  }

  .module {
    flex: 1 1 300px;
    min-width: 300px;
  }

  .calendar-day {
    font-size: 11px;
  }
}

@media (max-width: 768px) {
  .module {
    flex: 1 1 100%;
  }

  .recommendation-item, .activity-item {
    padding: 8px;
  }

  .recommendation-icon, .activity-icon {
    width: 32px;
    height: 32px;
    margin-right: 8px;
  }

  .news-item, .notice-item {
    padding: 6px;
  }

  .calendar-header {
    font-size: 11px;
  }

  .calendar-day {
    font-size: 10px;
  }

  .api-note-indicator {
    top: -40px;
    padding: 6px 10px;
    z-index: 1000;
  }

  .note-text {
    font-size: 11px;
  }
}

/* 确保所有父元素都不限制溢出 */
.module.card {
  overflow: visible !important;
}

.sidebar-container {
  overflow: visible !important;
}

.calendar-day-wrapper.has-note {
  overflow: visible !important;
}

/* 移除不需要的样式 */
.calendar-day.has-event::after,
.event-indicator,
.calendar-day.coming-soon,
.calendar-day.coming-soon::before {
  display: none;
}
</style>
